<?php    
        
require_once KERNEL.DS.'router.php';

class Dispatcher extends Object
{
    public $baseUrl;  
    
    /**
    * Var option request
    * 
    * @var Array
    */
    public $params = array();
    
    function __construct(){   
        $this->baseUrl = Input::get('url', 'str', ''); 
    }      
    
    public function dispatch() { 
        // Check router
        if(REWRITE) {
	        Router::connect(); 
		}
           
        // Check admin
        if($this->params['subfix'] === 'admin'){    
            /*if(!isset($_SESSION[NAME_SESSION_USER_SYSTEM]) && $Controller !== 'Login') {   
                Url::redirect(null, 'admin_login');     
            }
            elseif(isset($_SESSION[NAME_SESSION_USER_SYSTEM]) && $Controller === 'Login') {
                Url::redirect(null, 'admin_home');
            }*/
        }                                                                                                      

        if(!include(APP.DS.$this->params['subfix'].DS.'controllers'.DS.strtolower($this->params['controller'].'_controller') .'.php')){
            exit();
        }        
         
        if(IS_DEBUG) {        
            Debug::getInstance()->mark('Begin module', $this->params['controller'] .'_controller.php');
        }  
        $classController = $this->__classControler($this->params['controller']) .'Controller';  
        $controller = new $classController();
        
        if ((int)method_exists($classController, $this->params['action'])) { 
            echo $controller->run($this->params); 
        } else {
            /* Error Generation Code Here */
            exit();
        }    
        if(IS_DEBUG)
        {        
            Debug::getInstance()->mark('End script', 'index.php');
            echo '<div style="width: 1046px; overflow: auto;" id="jq-game-debug">'. Debug::debug() .'<hr />'. memory_get_usage() / 1000000 .'</div>';
        }  
    }
    
    /**
     * Rename class controller
     * 
     * @param String $class
     * @return String
     * @access Protected
     */
    function __classControler($class) {
        if(!substr_count($class, '_')){
            return ucfirst(strtolower($class));
        }
        $arrController = explode('_', $class);
        $classController = '';
        for($i=0;$i<sizeof($arrController);$i++) {
            $classController .= ucfirst(strtolower($arrController[$i]));   
        }        
        return $classController;  
    }
    
    /**
     * Get controller to use, either plugin controller or application controller
     *
     * @param array $params Array of parameters
     * @return mixed name of controller if not loaded, or object if loaded
     * @access private
     */
    function &__getController($params = null) {
        if (!is_array($params)) {
            $original = $params = $this->params;
        }
        $controller = false;
        $ctrlClass = $this->__loadController($params);
        if (!$ctrlClass) {
            if (!isset($params['plugin'])) {
                $params = $this->_restructureParams($params);
            } else {
                if (empty($original['pass']) && $original['action'] == 'index') {
                    $params['action'] = null;
                }
                $params = $this->_restructureParams($params, true);
            }
            $ctrlClass = $this->__loadController($params);
            if (!$ctrlClass) {
                $this->params = $original;
                return $controller;
            }
        } else {
            $params = $this->params;
        }
        $name = $ctrlClass;
        $ctrlClass = $ctrlClass . 'Controller';
        if (class_exists($ctrlClass)) {
            if (strtolower(get_parent_class($ctrlClass)) === strtolower($name . 'AppController') && empty($params['plugin'])) {
                $params = $this->_restructureParams($params);
                $params = $this->_restructureParams($params, true);
            }
            $this->params = $params;
            $controller =& new $ctrlClass();
        }
        return $controller;
    }
    
    /**
     * Load controller and return controller class
     *
     * @param array $params Array of parameters
     * @return string|bool Name of controller class name
     * @access private
     */
    function __loadController($params) {
        $pluginName = $pluginPath = $controller = null;
        if (!empty($params['plugin'])) {
            $this->plugin = $params['plugin'];
            $pluginName = Inflector::camelize($params['plugin']);
            $pluginPath = $pluginName . '.';
            $this->params['controller'] = $this->plugin;
            $controller = $pluginName;
        }
        if (!empty($params['controller'])) {
            $this->params['controller'] = $params['controller'];
            $controller = Inflector::camelize($params['controller']);
        }
        if ($pluginPath . $controller) {
            if (App::import('Controller', $pluginPath . $controller)) {
                return $controller;
            }
        }
        return false;
    }
    
    protected function getModule(){   
        if(!isset($_GET['controller'])){
            $_GET['controller'] = $this->controller = (!defined('MODULE_DEFAULT') ? 'home' : MODULE_DEFAULT); 
        }
        else{
			if(substr($_GET['controller'], 0, 5) === 'admin'){
				$this->prefix = 'admin'.DS;	
				$this->controller = substr($_GET['controller'], 6);
            }
            else {
                $this->controller = $_GET['controller'];
			}
        }  
              
        if(!substr_count($this->controller, '_')){
            return ucfirst(strtolower($this->controller));
        }
        $arrController = explode('_', $this->controller);
        $controllerName = '';
        for($i=0;$i<sizeof($arrController);$i++) {
            $controllerName .= ucfirst(strtolower($arrController[$i]));   
        }         echo $controllerName;
        return $controllerName;  
    }
    
    protected function getRouter()
    {          
        require_once CONFIG.DS.'router.php';
        
        foreach($router as $key => $val)
        { 
            if(preg_match('#^'.$key.'$#', $this->url))
            { 
                if(strpos($val, '$') !== false && strpos($key, '(') !== false)
                { 
                    $val = preg_replace('#^'.$key.'$#', $val, $this->url); 
                }         
                $arrUrl = explode('&', $val);   
                foreach($arrUrl as $_url){ 
                    $_aUrl = explode('=', $_url);  
                    $_GET[$_aUrl[0]] = $_aUrl[1]; 
                    if($_aUrl[0] === 'controller'){  
                    	if(substr($_aUrl[1], 0, 5) === 'admin'){
							$this->prefix = 'admin'.DS;	
							$this->controller = substr($_aUrl[1], 6);
                    	}
                    	else {
                        	$this->controller = $_aUrl[1];
						}
                    }
                } 
                break; 
            } 
        }  
    }
    
    function __destruct() {
        
    } 
}
?>
